<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

final class User extends Authenticatable
{
    use HasFactory;

    private const REMEMBER_AUTH_SECONDS = 300;

    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_full_name',
        'user_login',
        'user_password',
    ];

    /**
     * @var array<string, string>
     */
    protected $casts = [
        'user_created_at' => 'datetime:d.m.Y',
    ];

    /**
     * @var string
     */
    protected $primaryKey = 'user_id';

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'user_password',
        'user_remember_token',
    ];

    /**
     * @var array
     */
    protected $visible = [
        'user_id',
        'user_full_name',
        'user_created_at',
        'roles_names',
    ];

    /**
     * @var array
     */
    protected $appends = [
        'roles_names',
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
    }

    public function getAuthPassword()
    {
        return $this->user_password;
    }

    public function getRolesNamesAttribute()
    {
        return \implode(', ', $this->roles->pluck('role_name')->all());
    }

    /**
     * @return bool
     */
    public function hasAbility(array $roles, array $permissions)
    {
        $key = 'user.' . $this->user_id . '.roles.' . \implode('', $roles) . '.permissions:' . \implode('', $permissions);
        return \Cache::remember($key, self::REMEMBER_AUTH_SECONDS, function() use ($roles, $permissions) {
            return $this->hasRole($roles) && $this->hasPermission($permissions);
        });
    }

    /**
     * @param string|array $name
     */
    public function hasRole($name)
    {
        if (empty($name)) {
            return true;
        }

        $roles_names = \is_array($name) ? $name : [$name];

        $roles_count = $this->roles()
            ->whereIn('role_name', $roles_names)
            ->count();

        return $roles_count === \count($roles_names);
    }

    /**
     * @param string|array $name
     */
    public function hasPermission($name)
    {
        if (empty($name)) {
            return true;
        }

        $permissions_names = \is_array($name) ? $name : [$name];

        $roles_permissions_count = $this->roles()
            ->withCount([
                'permissions' => static function ($query) use ($permissions_names) {
                    $query->whereIn('permission_name', $permissions_names);
                }
            ])
            ->pluck('permissions_count')
            ->sum();

        return $roles_permissions_count === \count($permissions_names);
    }
}
